import flask
from gevent import monkey

# 多线程支持
monkey.patch_all()
static_folder = '../static'
static_url_path = '/static'


def createFlaskApp():
    from flask import Flask
    from src.util.Log import logging
    import os
    app = Flask('app', static_url_path=static_url_path, static_folder=static_folder)
    app.logger.handle = logging.getLogger('falsk.app').handle
    # app.config["UPLOAD_FOLDER"] = "static"  # 设置上传文件将存储的文件夹
    # app.config['SECRET_KEY'] = 'secret!'
    # if not os.path.exists(app.config["UPLOAD_FOLDER"]):
    #     os.makedirs(app.config["UPLOAD_FOLDER"])
    return app


# 创建flask app
def createSocketApp(app: flask.Flask):
    import importlib
    import pkgutil
    from src.util.Route import blu, setSocket
    from src.util.Cache import setCache
    from flask_socketio import SocketIO
    import multiprocessing
    # 注入缓存类
    setCache(app)

    # websocket
    socket = SocketIO(app, cors_allowed_origins='*', async_mode='gevent', threading=True,
                      processes=multiprocessing.cpu_count())
    # 注入socket
    setSocket(socket)

    # 包扫描函数
    def pack_scan(pack_name: list[str]):
        def import_submodules(package):
            """递归导入子模块"""
            for _, module_name, _ in pkgutil.iter_modules(package.__path__):
                importlib.import_module(package.__name__ + '.' + module_name)

        for pk in pack_name:
            import_submodules(importlib.import_module(pk))

    # 包扫描扫描路由和拦截器(加载所有路由)
    pack_scan(['src.interceptor', 'src.controller'])
    app.register_blueprint(blu)
    return socket
